/* 3. 增加书籍数量 */

'use strict';

const CHECK = require('../myUtil/formatCheck');
const db = require('../../coSqlite3');
const HTM = require('../myUtil/lib').html;

exports.increaseBook = function* (req, res) {
    console.log("----------------------3. 增加书籍数量\n");
    let bID = req.body.bID;
    let bCnt = req.body.bCnt;

    let htm = HTM.divBegin + 2 + HTM.divEnd + '提交的参数有误：';

    if (bID == '') {
      return HTM.begin + htm + '书号不能为空' + HTM.end;
    } else if (bID.length > 30) {
      return HTM.begin + htm + '书号长度不能超过30' + HTM.end;
    }

    if (bCnt == '') {
      return HTM.begin + htm + '数量不能为空' + HTM.end;
    } else if (!CHECK.isNumber(bCnt)) {
      return HTM.begin + htm + '数量必须是数字' + HTM.end;
    } else if (bCnt <= 0) {
      return HTM.begin + htm + '数量必须大于0' + HTM.end;
    }


    htm = HTM.divBegin + 1 + HTM.divEnd;
    try {
        let rows = yield db.execSQL('SELECT count(bid) as count FROM book WHERE bID = ?', [bID]);
        
        if (rows[0].count == 0) {
            return HTM.begin + htm + '该书不存在' + HTM.end;
        }

        let row = rows[0];
        yield db.execSQL('UPDATE book SET bCnt = bCnt + ?, bTrueCnt = bTrueCnt + ? WHERE bID = ?', [bCnt, bCnt, bID]);

    } catch (err) {
        htm = HTM.divBegin + 3 + HTM.divEnd + "数据库执行失败: ";
        return HTM.begin + htm + HTM.end;
    }
    htm = HTM.divBegin + 0 + HTM.divEnd;
    return HTM.begin + htm + '成功' + HTM.end;
}